<template>
  <div>
    <!-- 查询表单 -->
    <el-form :inline="true" :model="queryParams" class="demo-form-inline" @submit.prevent>

      <el-form-item label="姓名" style="width: 220px">
        <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable/>
      </el-form-item>
      <el-form-item label="用户名" style="width: 220px">
        <el-input v-model="queryParams.username" placeholder="请输入用户名" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchProductList">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
        <el-button v-if="isAdmin" type="primary" @click="openAddDialog">添加用户</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <Table
        :projectList="userList"
        :columns="columns"
        :queryParams="queryParams"
        :total="total"
        :loading="loading"
        @update="handleUpdate"
        @remove="handleRemove"
        @detail="handleDetail"
        detail-button-text="信息"
        @page-change="handlePageChange"
    />


    <FormDialog
        v-model:visible="editDialogVisible"
        width="400"
        :model="currentRow"
        :columns="Columns"
        :title="dialogTitle"
        :okText="okButtonText"
        formWidth="350px"
        @save="handleSave"
    />

  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import axios from 'axios'
import Table from "@/components/el-table/Table.vue";
import FormDialog from "@/components/FormDialog/FormDialog.vue";
import { computed } from 'vue'

const api = axios.create({
  baseURL: "https://pro.lkkj.xyz",
  // baseURL: "http://localhost:8080",
  timeout: 50000,
})

import { useAuthStore } from '@/stores/auth.js'

const authStore = useAuthStore()

const isAdmin = computed(() => {
  return authStore.token === 'admin'
})

const dialogTitle = computed(() => {
  return currentRow.value.id ? '编辑人员信息' : '新增人员'
})

const okButtonText = computed(() => {
  return currentRow.value.id ? '保存' : '新增'
})




onMounted(() => {
  fetchProductList()
})

//user 表格数据
const userList = ref([])
const total = ref(0)
const loading = ref(false)
const columns = ref([
  {prop: 'name', label: '姓名', minWidth: 120},
  {prop: 'username', label: '用户名', minWidth: 120},
  {prop: 'password', label: '密码', minWidth: 120},
  { prop: 'status', label: '启用状态', minWidth: 120, isSwitch: true, activeValue: 1, inactiveValue: 0, disabled: true },
]);


const handleUpdate = (row) => {
  currentRow.value = {...row}
  editDialogVisible.value = true
};
const handleRemove = (row) => {
  ElMessageBox.confirm(`确定要删除用户【${row.username || row.name || ''}】吗？`, '删除确认', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(() => {
        // 用户点击确认后执行删除请求
        api.delete('/user/delete/' + row.id)
            .then(res => {
              if (res.data.code === 200) {
                ElMessage.success('删除成功')
                fetchProductList()
              } else {
                ElMessage.error(res.data.message || '删除失败')
              }
            })
            .catch(error => {
              console.error(error)
              ElMessage.error('请求失败，请稍后重试')
            })
      })
      .catch(() => {
        // 用户点击取消，什么也不做
      })
}
// 重置查询
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    code: '',
    name: '',
    client: '',
    status: ''
  }
  fetchProductList()
}

onMounted(() => {
  fetchProductList()
})

const handlePageChange = (page) => {
  queryParams.value.pageNum = page
  fetchProductList()
}

const queryParams = ref({

  name: '',
  username: '',
  pageNum: 1,
  pageSize: 10
})

// 获取项目列表
const fetchProductList = async () => {
  try {
    const response = await api.get('/user/pageList', {
      params: queryParams.value
    })
    const res = response.data
    if (res.code === 200) {
      userList.value = res.data.list
      total.value = res.data.total

    } else {
      ElMessage.error(res.message || '获取用户列表失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('请求失败')
  }
}


//编辑表单
const editDialogVisible = ref(false);
const currentRow = ref({});
const Columns = [
  {prop: 'name', label: '姓名', type: 'text'},
  {prop: 'username', label: '用户名', type: 'text'},
  {prop: 'password', label: '密码', type: 'text'},
  {
    prop: 'status',
    label: '状态',
    type: 'select',
    options: [
      { label: '启用', value: '1' },
      { label: '禁用', value: '0' },
    ],
  },
]

const openAddDialog = () => {
  currentRow.value = {
    name: '',
    username: '',
    password: '',
    status: ''
    // 不带 id → 表示新增
  }
  editDialogVisible.value = true
}



const handleSave = async (row) => {
  try {
    const url = row.id ? '/user/update' : '/user/add'
    const response = await api.post(url, row)
    if (response.data.code === 200) {
      ElMessage.success('新增成功')
      editDialogVisible.value = false
      await fetchProductList()
    } else {
      ElMessage.error(response.data.message || '保存失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('请求失败，请稍后重试')
  }
}


//打开授权
const dialogVisible = ref(false)

const handleDetail = (row) => {
  dialogVisible.value = true
};



</script>

<style scoped>
.demo-form-inline {
  margin-bottom: 20px;
}

</style>
